from flask import Blueprint, request, send_file, jsonify, redirect
from application.models.users.user import *
from application.tools.myredis import r
from application.tools.myjwt import myjwt
import json

course_blue = Blueprint("courseblue", __name__)

@course_blue.route("/addCourse",methods=['POST'])
def addCourse():
    try:
        # 获取参数
        data = json.loads(request.data)
        # 写入课程表
        course = Course(name=data['name'],url=data['url'],descrip=data['desc'],ctype=data['type'])
        db.session.add(course)
        # 获取新加的课程id
        scourse = Course.query.filter(Course.name == data['name']).first()
        # 写入课程标签表
        for i in data['tags']:
            # 查询标签表
            # tag = Tags.query.filter(Tags.id == i).first()
            # scourse.tags.append(tag)
            sql = "insert into course_tag(courseid,tagid) values(%d,%d)"%(scourse.id,int(i))
            db.session.execute(sql)
        # 课程分类表
        for i in data['ctype']:
            sql = "insert into course_cate(courseid,course_typeid) values(%d,%d)"%(scourse.id,int(i))
            db.session.execute(sql)
        db.session.commit()
    except:
        db.session.rollback()
    return jsonify({'code':200})

# import math
# @course_blue.route("/getCourse")
# def getCourse():
#     # 获取参数page
#     page = int(request.args.get("page"))
#     #获取上线、即将上线
#     online = int(request.args.get('is_publish'))
#     # 获取类别
#     types = int(request.args.get("types"))
#     # 查询总条数
#     if types == 0:
#         total = Course.query.filter(Course.is_publish == online).count()
#     else:
#         total = Course.query.filter(Course.is_publish==online,Course.ctype==types).count()
#     # 定义每页显示多少条
#     page_size = 2
#     # 查询当前页记录
#     start = math.ceil((page-1)*page_size)
#     # select * Course.query.offset start,page_size
#     # 获取排序字段
#     orderpara = request.args.get('orderpara')
#     if orderpara == 'new':
#         if types == 0:
#             course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#         else:
#             course = Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish == online,Course.ctype==types).offset(start).limit(page_size).all()
#     else:
#         course = Course.query.order_by(Course.views.desc()).filter(Course.is_publish == online).offset(start).limit(page_size).all()
#     print("====================",course)
#     list = [{
#         "id":i.id,
#         "name":i.name,
#         "url":i.url,
#         "views":i.views
#     }for i in course]
#     # 返回结果
#     return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})

import math
@course_blue.route("/getCourse")
def getCourse():
    # 获取当前页面
    page = int(request.args.get("page"))
    page_size = 2
    # 获取条件
    #获取上线、即将上线
    online = int(request.args.get('is_publish'))
    # 获取类别
    types = int(request.args.get("types"))
    # 获取标签
    tags = int(request.args.get("tags"))
    # 获取排序字段
    orderpara = request.args.get('orderpara')

    # 重构where条件
    where = "1=1"

    if online:
        where = where + " and c.is_publish=" + str(online)

    if types>0:
        where = where + " and c.ctype=" + str(types)

    # 排序
    orderby = " order by c.views desc"
    if orderpara == "new":
        orderby = " order by c.create_time desc"
    start = math.ceil((page-1)*page_size)
    # 查询一有多少条记录
    if tags > 0:
        countsql = "select count(c.id) as tcount from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid="+str(tags)+" and "+where
    else:
        countsql = "select count(c.id) as tcount from course as c where " + where
    cres = db.session.execute(countsql)
    cdata = cres.fetchone()
    total = cdata['tcount']
    print(total)
    # 查询当前页记录
    if tags > 0:
        # sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where is_publish=1 and ctype=1 and ct.tagid=1 order by c.create_time desc limit 0,2"
        sql = "select c.* from course as c inner join course_tag as ct on c.id=ct.courseid where ct.tagid=" + str(tags) + " and " + where + orderby + " limit " + str(start) + "," + str(page_size)
    else:
        sql = "select c.* from course as c where "+where+orderby+" limit "+str(start)+","+str(page_size)
    res = db.session.execute(sql)
    data = res.fetchall()
    list = [{
            "id":i.id,
            "name":i.name,
            "url":i.url,
            "views":i.views
    }for i in data]
    return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})

@course_blue.route("/getDetail")
def getDetail():
    courseid = request.args.get("id")
    userid = request.args.get("userid")
    course = Course.query.filter(Course.id == courseid).first()
    if userid:
        key = "collection" + str(userid) + "pro" + str(courseid)
        r.hash_add(key,"courseid",course.id)
        r.hash_add(key,"name",course.name)
        r.hash_add(key,"url",course.url)

    course = {
        "id":course.id,
        "name":course.name,
        "url":course.url,
      # "views":course.views,
      #   "tcount":course.tcount,
      #   "descrip":course.descrip
    }
    return jsonify({'code':200,"course":course})

@course_blue.route("/getViews")
def getViews():
    userid = request.args.get("userid")
    findkey = "collection" + str(userid) + "*"
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({'code':200,"list":reslist})
    # 加入购物车

@course_blue.route("/buy")
def buy():
    # 获取参数 userid courseid
    userid = request.args.get("userid")
    courseid = request.args.get("courseid")
    # 加减类型默认为+
    type = 1
    try:
        type = request.args.get("type")
    except:
        pass
    # 从hash中获取数据，如果存在数量+1, buy1course2
    key = "buy"+str(userid)+"course"+str(courseid)
    # 如果不存在存入redis hash
    flag = r.findkey_hash(key)
    # 存在
    if flag:
        # 数量+1
        ff = r.jiajian_hash(key,"number",1,type)
        if ff == False:
            return jsonify({'code':10010,"mes":"不能再减了"})
    else:
        r.hash_add(key,"id",courseid)
        r.hash_add(key,"number",1,)
        # 选中
        r.hash_add(key,"flag",'True')
    # 返回结果
    return jsonify({'code':200,"userid":userid,"courseid":courseid,"msg":"成功加入购物车"})


# 获取购物车
@course_blue.route("/mycart", methods=["GET"])
def mycart():
    # 获取参数userid
    userid = request.args.get("userid")
    # 从hash中获取商品id和数量
    key = "buy"+str(userid)+"*"
    goods = r.getvalues(key)
    glist =[]
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse={}
            for k,v in good.items():
                params = k.decode()
                values = v.decode()
                if params == "id":
                    tcourse = Tcourse.query.filter(Tcourse.id == values).first()
                    rescourse["id"] = tcourse.id
                    rescourse["name"] = tcourse.title
                    rescourse["url"] = tcourse.url
                    rescourse["price"] = tcourse.price
                if params == "number":
                    # 获取到数据库商品数量
                    rescourse["number"] = values
                    print("values",values)
            rescourse["total"] = int(rescourse["price"]) * int(rescourse["number"])
            # 计算总价格
            tmoney = float(tmoney) + float(rescourse["total"])
            tcount = int(tcount) + int(rescourse["number"])
            glist.append(rescourse)
    # 价格，图片，名字      从mysql中获取，从redis商品缓存中读取
    # 数据重组返回
    return jsonify({"code":200,"glist":glist,"tmoney":tmoney,"tcount":tcount})


# 获取训练营课程
@course_blue.route("/bootcamp", methods=["GET"])
def bootcamp():
    # 获取数据库存储的所有训练营课程
    trouse = Tcourse.query.all()
    # 序列化
    clist = [{"id":i.id,
              "name":i.title,
              "url":i.url,
              "price":i.price,
              "store":i.store,
              "intor":i.intro
              }for i in trouse]
    # 返回
    return jsonify({"code":200,"clist":clist})
# 获取训练营课程
@course_blue.route("/getBootcamp")
def getBootcamp():
    # 查询训练营课程
    bootcamp = Tcourse.query.all()
    bootlist = [{
        "id":i.id,
        "title":i.title,
        "url":i.url,
        "price":i.price,
        "intro":i.intro
    }for i in bootcamp]

    # 返回数据
    return jsonify({"code":200,"bootlist":bootlist})

#修改单个的选中状态
@course_blue.route("/modifyStatus")
def modifyStatus():
    # 如果true改为false，如果false改为true
    #获取参数 userid goodsid
    userid = request.args.get('userid')
    cid = request.args.get('cid')
    #获取原来的状态判断
    key = "buy"+str(userid)+'course'+str(cid)
    flag = r.getall_hash(key,'flag')
    # 设置默认为选中
    cflag = True
    if flag:
        flag = flag.decode()
        # 根据返回结果选择相反的值
        if flag == True:
            cflag=flag

        r.hash_add(key,'flag',cflag)
        return jsonify({"code":200})

